﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Web.Api.Server.Models;

namespace Web.Api.Server.ViewModels
{
    public class ShopsPostViewModel : IValidatableObject
    {
        public int? Id { get; set; }
        public string Name { get; set; }

        public string Describe { get; set; }

        public string Mobile { get; set; }

        public string WeChat { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            var shop = db.Shops
                .WhereIf(Id == null, s => s.Name == Name)
                .WhereIf(Id != null, s => s.Name == Name && s.Id != Id)
                .First();
            if (shop != null)
            {
                yield return new ValidationResult("店铺名被占用.", new[] { nameof(Name) });
            }
        }
    }
}
